package DAO;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Vector;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import server.main.server_main;

// 处理与机器人聊天的数据库历史记录
public class ChatDao {
	private Connection conn;
	private static final Logger logger = Logger.getLogger(ChatDao.class.getName()); // 日志库
	public ChatDao(Connection conn) {
		this.conn = conn;
        // 设置日志级别
        logger.setLevel(Level.INFO);
        // 创建一个文件处理器
        try {
        	String path = "." + File.separator + "log" + File.separator + "chatDao.log"; //   ./log/xxx.log
            FileHandler fileHandler = new FileHandler(path);
            fileHandler.setLevel(Level.INFO);

            // 创建一个日志格式化器
            Formatter formatter = new SimpleFormatter();
            fileHandler.setFormatter(formatter);

            // 将处理器添加到日志记录器
            logger.addHandler(fileHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	//插入一行数据
	public boolean Insert(int userId, int isMachine, String mes)
	{
		int rs = 0;
		String sql = "INSERT INTO chat_machine(user_id, message, time, is_machine) VALUES(?,?,?,?)";
		try {
			 LocalDateTime currentTime = LocalDateTime.now();
			 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			 String dateString = currentTime.format(formatter);
			 
			 System.out.println(dateString);
			 PreparedStatement stmt = conn.prepareStatement(sql);
			 stmt.setInt(1, userId);
			 stmt.setString(2, mes);
		     stmt.setString(3, dateString);
		     stmt.setInt(4, isMachine);
		     rs = stmt.executeUpdate();
		} catch(SQLException e) {
			e.getMessage();
		}
		if(rs > 0) {     //rs表示插入操作影响的行数 
			System.out.println("插入成功！");
			logger.info("插入成功");
			return true;
		} else {
			System.out.println("插入失败！");
			logger.info("插入失败");
			return false;
		}
	}
	
	//查询数据
	public Vector<model.Message> Query(int userId) {
		System.out.println("开始查询机器聊天历史");
		logger.info("开始查询机器聊天历史");
		Vector<model.Message> v = new Vector<>();
		ResultSet rs = null;
		String sql = "SELECT * FROM chat_machine where user_id = ?";
		try {
			PreparedStatement stmt = conn.prepareStatement(sql);
			stmt.setInt(1, userId);
			rs = stmt.executeQuery();
		} catch(SQLException e) {
			e.getMessage();
		}
		try {
			while(rs.next()) {
				model.Message mes = new model.Message();
				mes.setRoomID(rs.getInt("is_machine")); // roomId用来当isMachine
				mes.setText(rs.getString("message"));
				mes.setUserID(rs.getInt("user_id"));
				mes.setTime(rs.getString("time"));
				v.add(mes);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return v;
	}
}
